package com.cnooc.zyfx;


import com.cnooc.zyfx.db.DBHandler;
import com.cnooc.zyfx.entity.Entities;
import com.github.thorqin.toolkit.Application;
import com.github.thorqin.toolkit.annotation.Service;
import com.github.thorqin.toolkit.db.DBService;
import com.github.thorqin.toolkit.utility.ConfigManager;
import com.github.thorqin.toolkit.utility.Localization;
import com.github.thorqin.toolkit.utility.MimeUtils;
import com.github.thorqin.toolkit.utility.Serializer;
import com.github.thorqin.toolkit.validation.annotation.Validate;
import com.github.thorqin.toolkit.validation.annotation.ValidateString;
import com.github.thorqin.toolkit.web.HttpException;
import com.github.thorqin.toolkit.web.WebApplication;
import com.github.thorqin.toolkit.web.annotation.*;
import com.github.thorqin.toolkit.web.router.WebContent;
import com.github.thorqin.toolkit.web.session.WebSession;
import com.github.thorqin.toolkit.web.utility.ServletUtils;
import com.github.thorqin.toolkit.web.utility.UploadManager;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;

@WebModule(value="/api")
public class resourceModule {

    @Service("db")
    DBService db;
	
	@Service("application")
    WebApplication app;
	
    @Service("sqlServer")
    DBService msdb;
    
    private final static int maxUploadSize = 10;
    
//    @WebEntry(method = HttpMethod.POST)
//    WebContent upload(HttpServletRequest request, HttpServletResponse response, Localization loc) throws Exception {
//        ConfigManager configManager = WebApplication.get().getConfigManager();
//        UploadManager uploadManager = app.createUploadManager();
//        uploadManager.setFileSuffix("xlsx");
//        List<UploadManager.FileInfo> infos = uploadManager.saveUploadFiles(request,
//                configManager.getInteger("maxUploadSize", maxUploadSize) * 1024 * 1024);
//        if (infos.size() > 0) {
//            UploadManager.FileInfo info = infos.get(0);
//            // Since IE8,IE9 doesn't support application/json mime type in iframe,
//            // so I have to send response in plain/text type.
//            return WebContent.text(Serializer.toJsonString(info));
//        } else {
//            throw new HttpException(400, "unsupported.file.type", loc);
//        }
//    }  
//    
    
    
    @WebEntry(method = HttpMethod.POST)
    public WebContent upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UploadManager uploadManager = app.createUploadManager();
        uploadManager.setRestriction(".+");
        try {
            List<UploadManager.FileInfo> infos = uploadManager.saveUploadFiles(request, 1024 * 1024 * 50); // 10K
            if (infos.size() > 0) {
                return WebContent.text(Serializer.toJsonString(infos.get(0)));
            } else {
            	return WebContent.text("{\"error\":\"文件类型错误\"}");
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            return WebContent.text("{\"error\":\"大小超过限制\"}");
        }
    }
//    
//    public static class FileDownload {
//		@ValidateString
//		public String id;
//	}
//    @WebEntry(method = HttpMethod.POST)
//	public void download(HttpServletRequest request, HttpServletResponse response,@Entity @Validate FileDownload file) throws IOException, ServletException  {
//    	
//	}
//    
    
    public static class UploadFile {
        @ValidateString
        public String fileId;
        @ValidateString
        public String fileName;
    }
    private List<UploadFile> savedFiles = new LinkedList<>();
//    @WebEntry(method = HttpMethod.POST)
//    public WebContent upload(HttpServletRequest request,
//                             Localization loc) throws ServletException, FileUploadException, IOException {
//        UploadManager uploadManager = app.createUploadManager();
//        uploadManager.setRestriction(".+");
//        List<UploadManager.FileInfo> infos = uploadManager.saveUploadFiles(request);
//        if (infos.size() > 0) {
//            UploadManager.FileInfo info = infos.get(0);
//         //   String filePath = uploadManager.getFilePath(info.fileId);
//           // Long length= new File(filePath).length();
//            return WebContent.text(Serializer.toJsonString(info));
//        } else {
//            Map<String, String> error = new HashMap<>();
//            error.put("error", loc.get("message.upload.failed"));
//            return WebContent.text(Serializer.toJsonString(error));
//        }
//    }

    public static class DownloadFile{
    	  @ValidateString
          public String fileId;
    }
    @WebEntry(method = {HttpMethod.POST, HttpMethod.GET})
    public void download(@Entity DownloadFile file ,
                         HttpServletRequest request,
                         HttpServletResponse response,
                         Localization loc) throws IOException {
         UploadManager uploadManager = app.createUploadManager();
        UploadManager.FileInfo fileInfo = uploadManager.getFileInfo(file.fileId);
        String filePath = uploadManager.getFilePath(file.fileId);
        if (fileInfo != null) {
            ServletUtils.download(request, response, new File(filePath), fileInfo.fileName, fileInfo.mimeType);
        } else {
            throw new HttpException(404, "message.file.not.found", loc);
        }
    }

    @WebEntry(method = HttpMethod.POST)
    public void submit(@Entity @Validate UploadFile fileInfo) {
        savedFiles.add(fileInfo);
    }

    @WebEntry(method = HttpMethod.GET)
    public WebContent list() {
        return WebContent.json(savedFiles);
    }
	
}

